package org.dromara.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.BusinessConfig;
import org.dromara.business.domain.Goods;
import org.dromara.business.domain.ShoppingCart;
import org.dromara.business.domain.bo.ShoppingCartBo;
import org.dromara.business.domain.vo.GoodsVo;
import org.dromara.business.domain.vo.ShoppingCartVo;
import org.dromara.business.mapper.ShoppingCartMapper;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.business.service.GoodsService;
import org.dromara.business.service.ShoppingCartService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 购物车Service业务层处理
 *
 * @author zlj
 * @date 2024-08-20
 */
@RequiredArgsConstructor
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    private final ShoppingCartMapper baseMapper;

    private final GoodsService goodsService;
    private final BusinessConfigService configService;

    /**
     * 查询购物车
     */
    @Override
    public ShoppingCartVo queryById(Long shoppingCartId) {
        return baseMapper.selectVoById(shoppingCartId);
    }

    /**
     * 查询购物车列表
     */
    @Override
    public TableDataInfo<ShoppingCartVo> queryPageList(ShoppingCartBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, LoginHelper.getUserId());
        Page<ShoppingCartVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(result.getRecords())) {
            List<String> ids = StreamUtils.toList(result.getRecords(), ShoppingCartVo::getGoodsCategory);
            List<BusinessConfig> configList = configService.lambdaQuery().in(BusinessConfig::getBusinessConfigId, ids).list();
            for (ShoppingCartVo record : result.getRecords()) {
                for (BusinessConfig businessConfig : configList) {
                    if (record.getGoodsCategory().equals(businessConfig.getBusinessConfigId().toString())) {
                        record.setGoodsCategory(businessConfig.getConfigName());
                        break;
                    }
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询购物车列表
     */
    @Override
    public List<ShoppingCartVo> queryList(ShoppingCartBo bo) {
        /*LambdaQueryWrapper<ShoppingCart> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);*/
        return null;
    }

    /*private LambdaQueryWrapper<ShoppingCart> buildQueryWrapper(ShoppingCartBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ShoppingCart> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, ShoppingCart::getUserId, bo.getUserId());
        lqw.eq(bo.getGoodsId() != null, ShoppingCart::getGoodsId, bo.getGoodsId());
        lqw.eq(bo.getGoodsQuantity() != null, ShoppingCart::getGoodsQuantity, bo.getGoodsQuantity());
        lqw.eq(bo.getGoodsPrice() != null, ShoppingCart::getGoodsPrice, bo.getGoodsPrice());
        lqw.like(StrUtil.isNotBlank(bo.getGoodsName()), ShoppingCart::getGoodsName, bo.getGoodsName());
        lqw.eq(StrUtil.isNotBlank(bo.getGoodsUrl()), ShoppingCart::getGoodsUrl, bo.getGoodsUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getGoodsCategory()), ShoppingCart::getGoodsCategory, bo.getGoodsCategory());
        lqw.eq(StrUtil.isNotBlank(bo.getGoodsAttr()), ShoppingCart::getGoodsAttr, bo.getGoodsAttr());
        lqw.orderByDesc(ShoppingCart::getCreateTime);
        return lqw;
    }*/

    /**
     * 新增购物车
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ShoppingCartBo bo) {

        Long goodsId = bo.getGoodsId();
        Integer isAdd = bo.getIsAdd();

        Goods goods = goodsService.getById(goodsId);
        if (ObjectUtil.equals(goods.getCreateBy(), LoginHelper.getUserId())) {
            throw new ServiceException("不能购买自己的任务");
        }

        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getGoodsId, goodsId);
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, LoginHelper.getUserId());
        ShoppingCart cart = this.getOne(shoppingCartLambdaQueryWrapper);

        if (cart == null) {
            //如果之前这个任务没有购物车
            GoodsVo goodsVo = goodsService.queryById(goodsId);
            if (goodsVo == null) {
                throw new RuntimeException("任务不存在");
            }
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setGoodsName(goodsVo.getName());
            shoppingCart.setGoodsPrice(goodsVo.getPrice());
            shoppingCart.setGoodsId(bo.getGoodsId());
            shoppingCart.setGoodsUrl(goodsVo.getUrl().toString());
            shoppingCart.setUserId(LoginHelper.getUserId());
            shoppingCart.setGoodsQuantity(1);
            return this.save(shoppingCart);
        } else {
            if (isAdd == 1) {
                //如果之前这个任务有购物车，并且是加
                cart.setGoodsQuantity(cart.getGoodsQuantity() + 1);
            } else {
                //如果之前这个任务有购物车，并且是减
                cart.setGoodsQuantity(cart.getGoodsQuantity() - 1);
                if (cart.getGoodsQuantity() == 0) {
                    return this.removeById(cart.getShoppingCartId());
                }
            }
            return this.updateById(cart);
        }
    }

    /**
     * 修改购物车
     */
    @Override
    public Boolean updateByBo(ShoppingCartBo bo) {
        ShoppingCart update = MapstructUtils.convert(bo, ShoppingCart.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ShoppingCart entity) {

    }

    /**
     * 批量删除购物车
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean clear() {
        return this.remove(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getCreateBy, LoginHelper.getUserId()));
    }
}
